package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.*;
import com.zb.extend.UserTypeKnowledgeTypeExtend;
import com.zb.mapper.ZjUserTypeKnowledgeTypeMapper;
import com.zb.result.PageUtil;
import com.zb.service.ZjKnowledgeTypeService;
import com.zb.service.ZjUserService;
import com.zb.service.ZjUserTypeKnowledgeTypeService;
import com.zb.service.ZjUserTypeService;
import com.zb.vo.UserKnowledgeTypeVo;
import com.zb.vo.UserTypeKnowledgeTypeListVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 用户分类知识库分类关联表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-11-14
 */
@Service
public class ZjUserTypeKnowledgeTypeServiceImpl extends ServiceImpl<ZjUserTypeKnowledgeTypeMapper, ZjUserTypeKnowledgeType> implements ZjUserTypeKnowledgeTypeService {
    @Resource
    private ZjKnowledgeTypeService knowledgeTypeService;
    @Resource
    private ZjUserTypeService userTypeService;
    @Resource
    private ZjUserService userService;

    // 修改用户知识库权限
    @Override
    public void save(Long custAccId, Long userTypeId, UserKnowledgeTypeVo userKnowledgeTypeVo) {
        if (CollectionUtil.isNotEmpty(userKnowledgeTypeVo.getDelKnowledgeTypeIds())) {
            this.removeByIds(userKnowledgeTypeVo.getDelKnowledgeTypeIds());
        }
        if (CollectionUtil.isEmpty(userKnowledgeTypeVo.getKnowledgeTypeVos())) {
            return;
        }
        QueryWrapper<ZjUserTypeKnowledgeType> wrapper = new QueryWrapper<>();
        wrapper.select("id", "knowledge_type_id");
        wrapper.eq("user_type_id", userTypeId);
        List<ZjUserTypeKnowledgeType> typeList = this.list(wrapper);

        userKnowledgeTypeVo.getKnowledgeTypeVos().forEach(t -> {
            ZjUserTypeKnowledgeType type = typeList.stream().filter(f -> Objects.equals(f.getKnowledgeTypeId(), t.getKnowledgeTypeId())).findFirst().orElse(null);
            if (null != type) {
                t.setId(type.getId());
            }
        });

        List<KnowledgeTypeRelationVo> newTypeList = new ArrayList<>();
        // 判断去重
        userKnowledgeTypeVo.getKnowledgeTypeVos().stream().filter(f -> null == f.getId() || f.getId() == 0).forEach(o -> {
            if (newTypeList.stream().noneMatch(t -> Objects.equals(t.getKnowledgeTypeId(), o.getKnowledgeTypeId()))) {
                newTypeList.add(o);
            }
        });
        userKnowledgeTypeVo.getKnowledgeTypeVos().stream().filter(f -> null != f.getId() && f.getId() > 0).forEach(o -> {
            if (newTypeList.stream().anyMatch(t -> Objects.equals(t.getKnowledgeTypeId(), o.getKnowledgeTypeId()))) {
                newTypeList.stream().filter(f1 -> Objects.equals(f1.getKnowledgeTypeId(), o.getKnowledgeTypeId())).forEach(t -> {
                    if (null == t.getId()) {
                        t.setId(o.getId());
                    }
                });
                return;
            }
            newTypeList.add(o);
        });

        List<ZjUserTypeKnowledgeType> adds = new ArrayList<>();
        List<ZjUserTypeKnowledgeType> updates = new ArrayList<>();
        ZjUserTypeKnowledgeType type = null;
        for (KnowledgeTypeRelationVo vo : newTypeList) {
            type = new ZjUserTypeKnowledgeType();
            BeanUtil.copyProperties(vo, type);
            if (null != type.getId()) {
                updates.add(type);
                continue;
            }
            type.setId(IdWorker.getId());
            type.setCustAccId(custAccId);
            type.setUserTypeId(userTypeId);
            adds.add(type);
        }
        if (CollectionUtil.isNotEmpty(adds)) this.saveBatch(adds);
        if (CollectionUtil.isNotEmpty(updates)) this.updateBatchById(updates);
    }

    // 根据客户分类ID获取知识库信息
    @Override
    public List<UserTypeKnowledgeTypeExtend> getByUserTypeIds(List<Long> userTypeIds) {
        if (CollectionUtil.isEmpty(userTypeIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjUserTypeKnowledgeType> wrapper = new QueryWrapper<>();
        wrapper.select("id", "user_type_id", "knowledge_type_id");
        wrapper.in("user_type_id", userTypeIds);
        List<ZjUserTypeKnowledgeType> typeList = this.list(wrapper);
        if (CollectionUtil.isEmpty(typeList)) {
            return new ArrayList<>();
        }

        QueryWrapper<ZjKnowledgeType> knowledgeTypeQueryWrapper = new QueryWrapper<>();
        knowledgeTypeQueryWrapper.select("id", "name");
        knowledgeTypeQueryWrapper.in("id", typeList.stream().map(ZjUserTypeKnowledgeType::getKnowledgeTypeId).distinct().toList());
        List<ZjKnowledgeType> knowledgeTypeList = knowledgeTypeService.list(knowledgeTypeQueryWrapper);

        return typeList.stream().map(type -> {
            UserTypeKnowledgeTypeExtend extend = new UserTypeKnowledgeTypeExtend();
            BeanUtil.copyProperties(type, extend);
            extend.setKnowledgeType(knowledgeTypeList.stream().filter(f -> Objects.equals(f.getId(), type.getKnowledgeTypeId())).map(ZjKnowledgeType::getName).findFirst().orElse(""));
            return extend;
        }).toList();
    }

    // 根据知识库分类ID获取客户分类
    @Override
    public List<UserTypeKnowledgeTypeExtend> getByKnowledgeTypeIds(List<Long> knowledgeTypeIds) {
        if (CollectionUtil.isEmpty(knowledgeTypeIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjUserTypeKnowledgeType> wrapper = new QueryWrapper<>();
        wrapper.select("id", "user_type_id", "knowledge_type_id");
        wrapper.in("knowledge_type_id", knowledgeTypeIds);
        List<ZjUserTypeKnowledgeType> typeList = this.list(wrapper);
        if (CollectionUtil.isEmpty(typeList)) {
            return new ArrayList<>();
        }

        QueryWrapper<ZjUserType> userTypeQueryWrapper = new QueryWrapper<>();
        userTypeQueryWrapper.select("id", "name");
        userTypeQueryWrapper.in("id", typeList.stream().map(ZjUserTypeKnowledgeType::getKnowledgeTypeId).distinct().toList());
        List<ZjUserType> userTypeList = userTypeService.list(userTypeQueryWrapper);

        return typeList.stream().map(type -> {
            UserTypeKnowledgeTypeExtend extend = new UserTypeKnowledgeTypeExtend();
            BeanUtil.copyProperties(type, extend);
            extend.setUserType(userTypeList.stream().filter(f -> Objects.equals(f.getId(), type.getUserTypeId())).map(ZjUserType::getName).findFirst().orElse(""));
            return extend;
        }).toList();
    }

    // 根据客户分类ID获取知识库类型权限列表
    @Override
    public Map<String, Object> getList(Long userTypeId, PageUtil pageUtil) {
        PageUtil.setPageLimit(pageUtil);
        QueryWrapper<ZjUserTypeKnowledgeType> wrapper = new QueryWrapper<>();
        wrapper.select("id", "user_type_id", "knowledge_type_id", "gmt_create", "gmt_update");
        wrapper.eq("user_type_id", userTypeId);
        Page<ZjUserTypeKnowledgeType> page = this.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), wrapper);

        List<ZjKnowledgeType> knowledgeTypeList = new ArrayList<>();
        List<Long> knowledgeTypeIds = page.getRecords().stream().map(ZjUserTypeKnowledgeType::getKnowledgeTypeId).distinct().toList();
        if (CollectionUtil.isNotEmpty(knowledgeTypeIds)) {
            QueryWrapper<ZjKnowledgeType> knowledgeTypeQueryWrapper = new QueryWrapper<>();
            knowledgeTypeQueryWrapper.select("id", "name");
            knowledgeTypeQueryWrapper.in("id", page.getRecords().stream().map(ZjUserTypeKnowledgeType::getKnowledgeTypeId).distinct().toList());
            knowledgeTypeList.addAll(knowledgeTypeService.list(knowledgeTypeQueryWrapper));
        }
        ZjUserType userType = userTypeService.getById(userTypeId);

        List<UserTypeKnowledgeTypeListVo> voList = page.getRecords().stream().map(type -> {
            UserTypeKnowledgeTypeListVo vo = new UserTypeKnowledgeTypeListVo();
            vo.setId(type.getKnowledgeTypeId());
            vo.setName(knowledgeTypeList.stream().filter(f -> Objects.equals(f.getId(), type.getKnowledgeTypeId())).map(ZjKnowledgeType::getName).findFirst().orElse(""));
            vo.setUserType(userType.getName());
            vo.setCreateTime(type.getGmtCreate());
            vo.setUpdateTime(type.getGmtUpdate());
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 获取移动端客户故障分类列表
    @Override
    public Map<String, Object> getUserMobileknowledgeTypeList(Long userId, PageUtil pageUtil) {
        ZjUser user = userService.getById(userId);
        if (null == user.getUserTypeId() || user.getUserTypeId() == 0) {
            return PageUtil.pageList(pageUtil.getPage(), pageUtil.getLimit(), 0L, new ArrayList<>());
        }
        PageUtil.setPageLimitMobile(pageUtil);
        QueryWrapper<ZjUserTypeKnowledgeType> wrapper = new QueryWrapper<>();
        wrapper.select("knowledge_type_id");
        wrapper.in("user_type_id", user.getUserTypeId());
        Page<ZjUserTypeKnowledgeType> page = this.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), wrapper);
        if (CollectionUtil.isEmpty(page.getRecords())) {
            return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), new ArrayList<>());
        }

        QueryWrapper<ZjKnowledgeType> knowledgeTypeQueryWrapper = new QueryWrapper<>();
        knowledgeTypeQueryWrapper.select("id", "name");
        knowledgeTypeQueryWrapper.in("id", page.getRecords().stream().map(ZjUserTypeKnowledgeType::getKnowledgeTypeId).distinct().toList())
                .eq("is_disabled", false);
        List<ZjKnowledgeType> knowledgeTypeList = knowledgeTypeService.list(knowledgeTypeQueryWrapper);

        List<UserTypeKnowledgeTypeListVo> voList = page.getRecords().stream().map(type -> {
            UserTypeKnowledgeTypeListVo vo = new UserTypeKnowledgeTypeListVo();
            vo.setId(type.getKnowledgeTypeId());
            vo.setName(knowledgeTypeList.stream().filter(f -> Objects.equals(f.getId(), type.getKnowledgeTypeId())).map(ZjKnowledgeType::getName).findFirst().orElse(""));
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }
}
